package com.inspur.edp.udt.designtime.manager.generatecmpcode.javacodegenerator;


import com.inspur.edp.bef.component.base.GspComponent;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.service.RefCommonService;
import com.inspur.edp.udt.designtime.api.entity.UnifiedDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.validation.ValidationInfo;
import com.inspur.edp.udt.designtime.api.exception.UdtModelErrorCodeEnum;
import com.inspur.edp.udt.designtime.api.exception.UdtModelException;
import com.inspur.edp.udt.designtime.api.utils.UdtUtils;
import com.inspur.edp.udt.designtime.manager.generatecomponent.ComponentGenUtil;
import com.inspur.edp.udt.designtime.manager.generatecomponent.JavaCompCodeNames;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

public abstract class JavaBaseCompCodeGenerator {

  ///#region 字段
  private String entityNamespace;
  private String apiNamespace;
  private RefCommonService lcmDtService;


  protected ValidationInfo vldInfo;
  protected String nameSpace;
  protected String entityClassName;
  protected String code;
  protected String packageName;

  private String privatePath;

  public final String getPath() {
    return privatePath;
  }

  public final void setPath(String value) {
    privatePath = value;
  }

  private RefCommonService getLcmDtService() {
    if (lcmDtService == null) {
      lcmDtService = SpringBeanUtils.getBean(RefCommonService.class);
    }
    return lcmDtService;
  }

  ///#endregion
  protected abstract String getBaseClassName();

  ///#region 构造函数
  protected JavaBaseCompCodeGenerator(UnifiedDataTypeDef udtDef, ValidationInfo vldInfo,
      String nameSpace, String path) {
    this.code = udtDef.getCode();
    this.packageName = udtDef.getDotnetAssemblyName();
    setPath(path);
    this.vldInfo = vldInfo;
    // NameSpace = getNameSpace(nameSpace);
    this.nameSpace = getNameSpace();
    this.entityClassName = udtDef.getGeneratedEntityClassInfo().getClassName();
    this.entityNamespace = udtDef.getGeneratedEntityClassInfo().getClassNamespace();
    this.apiNamespace = udtDef.getApiNamespace().getDefaultNamespace();
  }

  private String getNameSpace(String baseNameSpace) {
    String nameSpace = "%1$s.%2$s";
    return String.format(nameSpace, baseNameSpace + "." + code, getNameSpaceSuffix());
  }

  private String getNameSpace() {
    String nameSpace = "%1$s.%2$s";
    return String.format(nameSpace, packageName + "." + code, getNameSpaceSuffix());
  }

  protected abstract String getNameSpaceSuffix();

  /**
   * 获取当前构件名称
   */
  public final String getCompName() {
    if (UdtUtils.checkNull(vldInfo.getCmpId())) {
      return getInitializeCompName();
    }
    GspMetadata metadata = getLcmDtService().getRefMetadata(vldInfo.getCmpId());
    if (metadata == null) {
      throw UdtModelException.createException(UdtModelErrorCodeEnum.GSP_BEMODEL_UDT_MODEL_0005);
    }

    IMetadataContent content = metadata.getContent();
    String fullClassName = "";
//		if (content instanceof GspComponentMetadata)
//		{
//			GspComponentMetadata component = (GspComponentMetadata)content;
//			IGspComponent components = (IGspComponent)component.Content;
//			fullClassName = components.Method.ClassName;
//		}
//		else 
    if (content instanceof GspComponent) {
      GspComponent component = (GspComponent) ((metadata.getContent() instanceof GspComponent)
          ? metadata.getContent() : null);
      if(component != null){
        fullClassName = component.getMethod().getDotnetClassName();
      }

    } else {
      throw UdtModelException.createException(UdtModelErrorCodeEnum.GSP_BEMODEL_UDT_MODEL_0006);
    }

    String[] sections = fullClassName.split("[.]", -1);
    return sections[sections.length - 1];
  }

  ///#endregion

  ///#region 转换Java包名
  private String convertJavaImportPackage(String assemblyName) {
    return ComponentGenUtil.prepareJavaPackageName(assemblyName);
  }

  ///#endregion
  public final String generate() {
    StringBuilder result = new StringBuilder();
    ///#region package
    nameSpace = convertJavaImportPackage(nameSpace);
    result.append(JavaCompCodeNames.KeywordPackage).append(" ").append(nameSpace).append(";")
        .append(getNewline());

    generateImport(result);
    result.append("\n");
    result.append(JavaCompCodeNames.KeywordPublic).append(" ")
        .append(JavaCompCodeNames.KeywordClass).append(" ").append(getCompName()).append(" ")
        .append(JavaCompCodeNames.KeywordExtends).append(" ").append(getBaseClassName()).append(" ")
        .append("{").append(getNewline());

    javaGenerateField(result);
    result.append("\n");

    javaGenerateConstructor(result);
    result.append("\n");

    result.append(getIndentationStr()).append("@").append(JavaCompCodeNames.KeywordOverride)
        .append(getNewline());
    result.append(getIndentationStr()).append(JavaCompCodeNames.KeywordPublic).append(" ")
        .append(JavaCompCodeNames.KeywordVoid).append(" ").append("execute()").append(" ")
        .append("{").append(getNewline());

    result.append(getIndentationStr()).append("}").append(getNewline());

    javaGenerateExtendMethod(result);

    result.append(getNewline()).append("}");

    return result.toString();
  }

  ///#region 生成方法

  /**
   * 生成Using代码
   */

  private void generateImport(StringBuilder result) {
//		entityNamespace =String.format("%1$s%2$s",convertJavaImportPackage(entityNamespace),".*");
    entityNamespace = String.format("%1$s%2$s", entityNamespace, ".*");
    result.append(getImportStr(entityNamespace));
//		apiNamespace =String.format("%1$s%2$s",convertJavaImportPackage(apiNamespace),".*");
    apiNamespace = String.format("%1$s%2$s", apiNamespace, ".*");
    result.append(getImportStr(apiNamespace));
    javaGenerateExtendUsing(result);
  }

  protected abstract void javaGenerateExtendUsing(StringBuilder result);

  protected abstract void javaGenerateConstructor(StringBuilder result);

  protected void javaGenerateExtendMethod(StringBuilder result) {

  }

  protected void javaGenerateField(StringBuilder result) {

  }

  ///#endregion

  ///#region 通用方法

  protected final String getImportStr(String value) {
    return new StringBuilder(JavaCompCodeNames.KeywordImport).append(" ").append(value).append(";")
        .append(getNewline()).toString();
  }

  protected final String getNewline() {
    return "\r\n";
  }

  /**
   * 缩进
   */
  protected final String getIndentationStr() {
    return "\t";
  }

  /**
   * 双缩进
   */
  protected final String getDoubleIndentationStr() {
    return "\t\t";
  }

  ///#endregion

  protected abstract String getInitializeCompName();
}